package pub.cleangao.memm.util;

public class Scale62Convertor {


    private static final String CHARS = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
    private static final String negativeStrMark = "_";



    public static String scale10To62(long val, int length) {

        String rst = scale10To62(val);
        if (rst.length() > length) {
            return rst;
        }
        StringBuilder pad = new StringBuilder();
        for (int i = 0; i < length - rst.length(); i++) {
            pad.append("0");
        }
        return pad + rst;
    }


    public static String scale10To62(long val) {
        boolean negative = false;
        if (val < 0) {
            negative = true;
            val = Math.abs(val);
        }
        StringBuilder sb = new StringBuilder();
        if (negative) {
            sb.append(negativeStrMark);
        }
        int remainder;
        while (val > CHARS.length() - 1) {
            //从最后一位开始进制转换，取转换后的值，最后反转字符串
            remainder = Long.valueOf(val % CHARS.length()).intValue();
            sb.append(CHARS.charAt(remainder));
            val = val / CHARS.length();
        }
        //获取最高位
        sb.append(CHARS.charAt(Long.valueOf(val).intValue()));

        return sb.reverse().toString();
    }


    public static long scale62To10(String val) {
        if (val == null) {
            throw new NumberFormatException("null");
        }
        boolean negative = false;
        if (val.endsWith(negativeStrMark)) {
            negative = true;
            val = val.substring(0, val.length() - 1);
            if (val.trim().length() == 0) {
                return 0L;
            }
            val = val.toUpperCase();
        }
        String REGEX = "^[0-9A-Za-z]+$";
        if (!val.matches(REGEX)) {
            throw new IllegalArgumentException("this is an Invalid parameter:" + val);
        }
        String tmp = val.replace("^0*", "");

        long result = 0L;
        int index = 0;
        int length = tmp.length();
        for (int i = 0; i < length; i++) {
            index = CHARS.indexOf(tmp.charAt(i));
            result += (long) (index * Math.pow(CHARS.length(), length - i - 1));
        }
        return negative ? -result : result;
    }




}
